<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Exception;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Uploadify;
use Hangpu888\Hpadmin\model\UploadifyCate as ModelUploadifyCate;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\validate\UploadifyCate as ValidateUploadifyCate;

class UploadifyCate extends Controller
{
    /**
     * 分类列表
     *
     * @return void
     */
    public function index()
    {
        $data = ModelUploadifyCate::select()->toArray();
        return Json::successRes($data);
    }

    /**
     * 添加分类
     *
     * @return void
     */
    public function add()
    {
        try {
            // 获取数据
            $post = request()->post();

            // 数据验证
            hpValidate(new ValidateUploadifyCate,$post);

            // 重组数据
            $model = new ModelUploadifyCate;
            foreach ($post as $field => $value) {
                $model->$field = $value;
            }
            if ($model->save($post)) {
                return Json::success('添加成功');
            }else{
                throw new Exception('添加失败');
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 修改分类
     *
     * @return void
     */
    public function edit()
    {
        try {
            // 获取数据
            $id = request()->get('id');
            $post = request()->post();

            // 数据验证
            hpValidate(new ValidateUploadifyCate,$post);

            // 重组数据
            $map['id'] = $id;
            $model = ModelUploadifyCate::where($map)->find();
            foreach ($post as $field => $value) {
                $model->$field = $value;
            }
            if ($model->save($post)) {
                return Json::success('修改成功');
            }else{
                throw new Exception('修改失败');
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 删除分类
     *
     * @return void
     */
    public function del()
    {
        // 获取数据
        $id = request()->get('id');
        // 检测是否有附件
        if (Uploadify::where(['cid'=> $id])->count()) {
            return Json::fail('该分类下有附件');
        }
        $model = ModelUploadifyCate::where(['id'=> $id])->find();
        if (!$model) {
            return Json::fail('该分类不存在');
        }
        if ($model->delete()) {
            return Json::success('删除成功');
        }else{
            return Json::fail('删除失败');
        }
    }
}